import re
import paramiko

def convert_to_kb(size_str):
    unit_to_kb = {
        'KB': 1,
        'MB': 1024,
        'GB': 1024**2,
        'TB': 1024**3,
        'K': 1,
        'M': 1024,
        'G': 1024**2,
        'T': 1024**3,
    }
    
    matched = re.search(r'([\d.]+)([A-Za-z]*)', size_str)
    if matched is None :
        raise ValueError("Unsupported format. Please provide a valid size with a unit.")
    
    # 提取大小和单位
    size = float(matched.group(1))  # 转换为浮点数
    unit = matched.group(2).upper() if matched.group(2) else None  # 获取单位

    if unit and unit not in unit_to_kb:
        raise ValueError(f"Unsupported unit provided: {unit}. Supported units are: {', '.join(unit_to_kb.keys())}")

    # 如果没有单位，默认使用 K
    if unit is None:
        unit = 'K'  
        
    return int(size * unit_to_kb[unit])  # 计算并返回结果

# # 示例
# print(convert_to_kb('12TB'))  # 输出：2097152
# print(convert_to_kb('12T'))  # 输出：2097152
# print(convert_to_kb('0.1M'))  # 输出：2097152
# print(convert_to_kb('12'))  # 输出：2097152
# print(convert_to_kb('12M'))  # 输出：2097152


def get_available_disk_space(hostname, port, username, password, directory):
    try:
        # 创建SSH客户端
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # 连接到远程服务器
        client.connect(hostname, port=port, username=username, password=password)

        # 执行df命令以获取指定目录的磁盘空间信息
        command = f"df {directory}"
        stdin, stdout, stderr = client.exec_command(command)

        # 获取命令输出
        output = stdout.read().decode()
        error_output = stderr.read().decode()

        if error_output:
            print(f"Error: {error_output}")
            return None

        # 解析输出以获取可用磁盘空间
        lines = output.splitlines()
        if len(lines) < 2:
            print("Unexpected output format.")
            return None

        # 输出数据的第二行包含我们需要的信息
        disk_info = lines[1].split()
        available_space = disk_info[3]  # 第四个字段是可用空间

        return available_space

    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        client.close()
   

def check_disk_space(hostname, port, username, password, directory, required_space):   
    
    available_space = get_available_disk_space(hostname, port, username, password, directory)
    if not available_space:
        print(f"Get available disk space failed")
    
    # 比较可用空间和所需空间
    if convert_to_kb(available_space) >= convert_to_kb(required_space):
        print(f"The available disk space in '{directory}' meets the requirement of {required_space}.")
        return True
    else:
        print(f"The available disk space in '{directory}' does not meet the requirement of {required_space}.")
        return False

def get_db_file_store_path(dbinfo):
    pass



# 示例用法
hostname = "192.168.0.6"
port = 22  # 默认SSH端口
username = "kermit"
password = "Dfitc@123456"
directory = "/mnt/hdb/09.Shared"
required_space = '250G'
result = check_disk_space(hostname, port, username, password, directory, required_space)
print(result)